package com.baibei.ebec.totrade;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baibei.basic.BaibeiBasicDialogFragment;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.model.CouponInfo;
import com.baibei.model.PercentInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.TradeParams;
import com.baibei.model.TradeType;
import com.baibei.module.AppRouter;
import com.baibei.module.RechargeHelper;
import com.baibei.module.UserStatus;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.RxObservable;
import com.baibei.ui.AppUI;
import com.baibei.widget.BaibeiNumberBar;
import com.baibei.widget.dialog.TradeDialog;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.rae.swift.Rx;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.content.ContentValues.TAG;

/**
 * 订购交易
 * Created by ChenRui on 2017/8/7 0007 14:56.
 */
public class ToTradeFragment extends BaibeiBasicDialogFragment implements ToTradeContract.View, IQuotationEvent {

    @BindView(R2.id.tv_use_coupon_count)
    TextView mTvUseCouponCount;
    @BindView(R2.id.switch_button)
    SwitchButton mSwitchButton;
    Unbinder unbinder;
    @BindView(R2.id.tv_buy_percent)
    TextView tvBuyPercent;
    @BindView(R2.id.tv_sell_percent)
    TextView tvSellPercent;
    private ToTradeContract.Presenter mPresenter;
    private TextWatcher mTextWatcher;
    private List<CouponInfo> mCouponInfos;
    private List<Integer> mSuggestNumbers;
    private int mMaxCount;
    private Context mContext;
    ArrayList<ProductInfo> mlist;
    private ToTradeGoodsAdapter toTradeGoodsAdapter;
    private ArrayList<Double> lastPrices;

    public static ToTradeFragment newInstance(List<ProductInfo> list, ProductInfo product, TradeType type, List<CouponInfo> infos, List<Integer> numbers, int maxDefindCount) {
        Bundle args = new Bundle();
        args.putParcelable("productInfo", product);
        args.putString("type", type.name());
        args.putParcelableArrayList("coupons", (ArrayList<? extends Parcelable>) infos);
        args.putParcelableArrayList("list", (ArrayList<? extends Parcelable>) list);
        args.putIntegerArrayList("suggest", (ArrayList<Integer>) numbers);
        args.putInt("maxCount", maxDefindCount);
        ToTradeFragment fragment = new ToTradeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private TradeType mType;

    @BindView(R2.id.tv_dialog_title)
    TextView mTitleView;

    @BindView(R2.id.btn_price_customer)
    EditText mCustomerQuantityText;

    @BindView(R2.id.btn_ensure)
    Button mEnSureView;

    @BindView(R2.id.nb_up)
    BaibeiNumberBar mUpBar;

    @BindView(R2.id.nb_down)
    BaibeiNumberBar mDownBar;

    @BindView(R2.id.tv_amount)
    TextView mAmountView;

    @BindView(R2.id.tv_fee)
    TextView mFeeView;

    @BindView(R2.id.xianjia)
    LinearLayout xianjia;

    @BindView(R2.id.jiesuanjia)
    LinearLayout jiesuanjia;

    @BindView(R2.id.tv_use_ticket)
    TextView mTvUseTicket;

    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;

    private final TradeParams mParams = new TradeParams();

    private TradeConfirmFragment mConfirmFragment;

    private int bg;

    // 快速选择价格
    private List<Button> mQuickQuantityList = new ArrayList<>();

    //购买数量的选择position
    private int mCurrentItem;
    private ProductInfo mProductInfo;
    private CouponInfo mHasSuitable;

    //商品列表的选择position
    private int currentpos = 0;
    //自定义栏数字
    private int customerNum = 0;
    /**
     * 监听事件
     */
    private OnTradeSuccessListener mOnListener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new TradeDialog(getContext());
    }

    @Override
    protected void onBindView(View view) {
        ButterKnife.bind(this, view);
        xianjia.setSelected(mType == TradeType.BUY);
        jiesuanjia.setSelected(mType == TradeType.SELL);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mlist.get(0).setIschecked(true);

        toTradeGoodsAdapter = new ToTradeGoodsAdapter(mlist);
        toTradeGoodsAdapter.setItemBorder(mType == TradeType.BUY ? 1 : 2);
        bg = mType == TradeType.BUY ? R.drawable.bg_new_trade_buy_dialog_price : R.drawable.bg_new_trade_sell_dialog_price;

        toTradeGoodsAdapter.setOnitemclickListener(new ToTradeGoodsAdapter.ItemClickListener() {
            @Override
            public void onitemclick(int pos) {
                for (ProductInfo info : mlist) {
                    info.setIschecked(false);
                }
                mlist.get(pos).setIschecked(true);
                toTradeGoodsAdapter.notifyDataSetChanged();
                mRecyclerView.smoothScrollToPosition(pos);

                RxObservable.create(ApiFactory.getInstance().getTradeApi().getValidCouponList(mlist.get(pos).getProductId()), getContext().toString())
                        .subscribe(new ApiDefaultObserver<List<CouponInfo>>() {
                            @Override
                            protected void onError(String s) {
                                ToastUtils.showShortToast("获取对应商品的优惠券信息失败");
                            }

                            @Override
                            protected void accept(List<CouponInfo> couponInfos) {
                                mCouponInfos = couponInfos;

                                //自定义统计数清零
                                customerNum = 0;
                                mCustomerQuantityText.setText(null);

                                //消除所有flag
                                for (Button button : mQuickQuantityList) {
                                    FrameLayout layout = (FrameLayout) button.getParent();
                                    if (layout.getChildCount() > 1) {
                                        layout.removeViewAt(1);
                                    }
                                }

                                FrameLayout flayout = (FrameLayout) mCustomerQuantityText.getParent();

                                while (flayout.getChildCount() > 1) {
                                    flayout.removeViewAt(1);
                                }

                                addCouponFlag();
                            }
                        });

                //改变商品时重新计算订金、服务费
                mProductInfo = mlist.get(pos);
                currentpos = pos;
                calc();
            }
        });
        mRecyclerView.setAdapter(toTradeGoodsAdapter);
        for (ProductInfo info : mlist) {
            info.setIschecked(false);
        }
        mlist.get(mlist.indexOf(mProductInfo)).setIschecked(true);
        mRecyclerView.scrollToPosition(mlist.indexOf(mProductInfo));
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.widget_dialog_totrade;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(ToTradeFragment.STYLE_NO_TITLE, R.style.MyDialog);
        mProductInfo = getArguments().getParcelable("productInfo");
        mType = TradeType.valueOf(getArguments().getString("type", TradeType.BUY.name()));
        mCouponInfos = getArguments().getParcelableArrayList("coupons");
        mlist = getArguments().getParcelableArrayList("list");
        mSuggestNumbers = getArguments().getIntegerArrayList("suggest");
        mMaxCount = getArguments().getInt("maxCount", 1000);

        Log.e(TAG, "onCreatehh"+mProductInfo.toString() );
        Log.e(TAG, "onCreatehh"+mlist.toString() );
        //区分处理现价订货和结算价订货

        if (mProductInfo == null) {
            getActivity().finish();
            return;
        }

        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);

        mPresenter = inject(ToTradeContract.Presenter.class);


        mConfirmFragment = TradeConfirmFragment.newInstance(mParams);
        mConfirmFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (mConfirmFragment.isEnsure()) {
                    IAppDialog loading = AppUI.loading(getContext(), "订货中，请稍后..", 0.6f);
                    loading.setCanceledOnTouchOutside(false);
                    loading.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mPresenter.cancel();
                            mEnSureView.setEnabled(true);
                        }
                    });
                    mEnSureView.setEnabled(false);
                    mPresenter.trade();
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.resume();
    }

    @OnClick(R2.id.img_close)
    public void onCloseClick() {
        dismiss();
    }

    @OnClick(R2.id.iv_left)
    public void onLeftClick() {
        LogUtils.e("tags2", currentpos);
        if (currentpos == 0) return;
        for (ProductInfo info : mlist) {
            info.setIschecked(false);
        }
        --currentpos;
        mlist.get(currentpos).setIschecked(true);
        toTradeGoodsAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(currentpos);
        //改变商品时重新计算订金、服务费
        mProductInfo = mlist.get(currentpos);
        calc();
    }


    @OnClick(R2.id.iv_right)
    public void onRightClick() {
        LogUtils.e("tags2", currentpos);
        if (currentpos >=
                mlist.size() - 1) return;
        for (ProductInfo info : mlist) {
            info.setIschecked(false);
        }
        ++currentpos;
        mlist.get(currentpos).setIschecked(true);
        toTradeGoodsAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(currentpos);
        //改变商品时重新计算订金、服务费
        mProductInfo = mlist.get(currentpos);
        calc();
    }

    @OnClick(R2.id.xianjia)
    public void onXianjiaClick() {
        xianjia.setSelected(true);
        jiesuanjia.setSelected(false);
        mEnSureView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.buyColor));
        toTradeGoodsAdapter.setItemBorder(1);
        toTradeGoodsAdapter.notifyDataSetChanged();
        bg = R.drawable.bg_new_trade_buy_dialog_price;
        resetSuggestNumBorder();
    }

    @OnClick(R2.id.jiesuanjia)
    public void onJiesuanjiaClick() {
        xianjia.setSelected(false);
        jiesuanjia.setSelected(true);
        mEnSureView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.sellColor));
        toTradeGoodsAdapter.setItemBorder(2);
        toTradeGoodsAdapter.notifyDataSetChanged();
        bg = R.drawable.bg_new_trade_sell_dialog_price;
        resetSuggestNumBorder();
    }

    private void resetSuggestNumBorder() {
        Button button = mQuickQuantityList.get(mCurrentItem);
        button.setBackgroundResource(bg);
    }

    /**
     * 交易
     */
    @OnClick(R2.id.btn_ensure)
    public void onEnSureClick() {
        mParams.type = mType;
        mParams.quantity = getQuantity();
        mParams.upPercent = mUpBar.getValue();
        mParams.downPercent = mDownBar.getValue();

        mParams.lastPrice = lastPrices.get(currentpos);
        mParams.productId = Rx.parseInt(mlist.get(currentpos).getProductId());
        mParams.close = Rx.parseDouble(mProductInfo.getClosePrice());

        //#382 java.lang.IllegalStateException
        //This happens when we try to add same fragment or DialogFragment twice before dismissing,
        if (!mConfirmFragment.isAdded()) {
            mConfirmFragment.show(getFragmentManager(), mParams);
        }
        Log.e(TAG, "onEnSureClick: " + mlist.get(currentpos).getClosePrice());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.destroy();
        QuotationManager.getInstance().unregister(this);
        mQuickQuantityList.clear();
        mQuickQuantityList = null;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price10));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price50));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price100));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price200));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price300));

        if (mQuickQuantityList == null) return;
        if (mSuggestNumbers == null) return;
        //数量一致，才进行赋值
        if (mQuickQuantityList.size() == mSuggestNumbers.size()) {
            for (int i = 0; i < mQuickQuantityList.size(); i++) {
                Button button = mQuickQuantityList.get(i);
                button.setText(String.valueOf(mSuggestNumbers.get(i)));
            }
        }
        mQuickQuantityList.get(0).setSelected(true);
        //记录默认的体验券使用
        mSwitchButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
        onPriceClick(mQuickQuantityList.get(0));

        mTitleView.setText(mType == TradeType.BUY ? getString(R.string.title_trade_buy) : getString(R.string.title_trade_sell));

        // 结算价订货
        if (mType == TradeType.SELL) {
            mEnSureView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.sellColor));
        }

        mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                int value = Rx.parseInt(charSequence.toString());
                mCustomerQuantityText.removeTextChangedListener(mTextWatcher);
                if (value > mMaxCount) {
                    mCustomerQuantityText.setText(mMaxCount + "");
                    value = mMaxCount;
                    mCustomerQuantityText.setSelection(mCustomerQuantityText.length());
                } else if (value <= 0 && !TextUtils.isEmpty(charSequence)) {
                    mCustomerQuantityText.setText("1");
                    value = 1;
                    mCustomerQuantityText.setSelection(mCustomerQuantityText.length());
                }
                onCustomerPriceChanged();
                mCustomerQuantityText.addTextChangedListener(mTextWatcher);

                //bug---当不选择的时候，会默认使用上一个选择的数量，使用体验券
                isCouponValiable(value);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };

        //限制最大值
        mCustomerQuantityText.addTextChangedListener(mTextWatcher);
//        CashierInputFilter cashierInputFilter = new CashierInputFilter();
//        cashierInputFilter.setMaxValue(1000);
//        InputFilter[] inputFilter = {cashierInputFilter};
//        mCustomerQuantityText.setFilters(inputFilter);

        //添加可用券标识
        addCouponFlag();
        //获取订购比例
        mPresenter.getPercent();
    }

    /**
     * 添加体验券标识
     */
    private void addCouponFlag() {
        LogUtils.e("couponinfoss", mCouponInfos.toString());

        coupon:
        for (CouponInfo couponInfo : mCouponInfos) {
            for (Button button : mQuickQuantityList) {
                //如果有相应面值，显示flag
//                if (true){
                if (couponInfo.getFaceValue() == Rx.parseInt(button.getText())) {
                    showFlag(button);
                    continue coupon;
                }
            }

            //默认显示最大面额件数的券
            if (couponInfo.getFaceValue() > customerNum) {
                mCustomerQuantityText.setText(couponInfo.getFaceValue() + "");
                showFlag(mCustomerQuantityText);
                mCustomerQuantityText.requestFocus();
                mCustomerQuantityText.setSelection(mCustomerQuantityText.getText().toString().length());
                customerNum = couponInfo.getFaceValue();
            }
        }
    }

    private void showFlag(View button) {
        ImageView flag = new ImageView(getContext());
        flag.setImageResource(R.mipmap.icon_has_coupon);
        FrameLayout layout = (FrameLayout) button.getParent();
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.bottomMargin = 40;
        lp.gravity = Gravity.RIGHT | Gravity.TOP;
        flag.setLayoutParams(lp);
        layout.addView(flag);
    }

    /**
     * 加载产品信息
     */
    private void onLoadProductInfo(ProductInfo productInfo) {

    }

    public void onCustomerPriceChanged() {
        if (TextUtils.isEmpty(mCustomerQuantityText.getText())) {
            setCurrentItem(mCurrentItem); // 默认选择
        } else {
            setCurrentItem(-1);
        }

        // 计算价格
        calc();
    }

    @OnClick({R2.id.btn_price10,
            R2.id.btn_price50,
            R2.id.btn_price100,
            R2.id.btn_price200,
            R2.id.btn_price300})
    public void onPriceClick(View view) {
        mCustomerQuantityText.setText("");
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            Button button = mQuickQuantityList.get(i);
            button.setSelected(button == view);
            if (button == view) {
                button.setBackgroundResource(bg);
                mCurrentItem = i;
                isCouponValiable(Rx.parseInt(button.getText()));
            }
        }

        // 计算价格
        calc();
    }


    /**
     * 根据体验券，是否可用
     * 数量
     *
     * @param count count
     */
    private void isCouponValiable(int count) {
        mHasSuitable = null;
        mSwitchButton.setChecked(false);
        for (CouponInfo couponInfo : mCouponInfos) {
            if (couponInfo.getFaceValue() == count) {
                mHasSuitable = couponInfo;
            }
        }
        mSwitchButton.setEnabled(mHasSuitable != null);
        if (mHasSuitable != null) {
            mTvUseCouponCount.setText(String.format(getString(R.string.valiable_ticket_count), mHasSuitable.getFaceValue()));
        } else {
            mTvUseCouponCount.setText(R.string.no_valiable_ticket);
        }
    }

    /**
     * 是否选择
     * 记录参数
     */
    private SwitchButton.OnCheckedChangeListener mOnCheckedChangeListener = new SwitchButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(SwitchButton switchButton, boolean checked) {
            if (checked) {
                mParams.couponInfo = mHasSuitable;
                //订货服务费
                mFeeView.setText(Rx.formatPrice(0));
                mAmountView.setText(Rx.formatPrice(0));
                mTvUseTicket.setVisibility(View.VISIBLE);
            } else {
                mParams.couponInfo = null;
                mTvUseTicket.setVisibility(View.GONE);
                mFeeView.setText(Rx.formatPrice(mParams.fee));
                mAmountView.setText(Rx.formatPrice(mParams.amount));
            }
        }
    };


    /**
     * 找到当前选择的项目
     */
    protected int getCurrentItem() {
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            if (mQuickQuantityList.get(i).isSelected())
                return i;
        }
        return -1;
    }

    /**
     * 取消所有的选择状态
     */
    protected void setCurrentItem(int position) {
        if (position >= 0) {
            mCurrentItem = position;
        }
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            mQuickQuantityList.get(i).setSelected(i == position && position >= 0);
        }
    }

    /**
     * 获取价格
     */
    protected int getQuantity() {
        int position = getCurrentItem();
        CharSequence text;
        if (position >= 0) {
            text = mQuickQuantityList.get(position).getText();
        } else {
            text = mCustomerQuantityText.getText();
        }
        return Rx.parseInt(text);
    }

    public ProductInfo getProduct() {
        return mProductInfo;
    }

    /**
     * 计算价格已经订货服务费
     */
    public void calc() {
        int quantity = getQuantity();
        double amount = mProductInfo.getPrice() * quantity; // 订金
        double fee = mProductInfo.getFee() * quantity; //订货服务费
        mParams.amount = amount;
        mParams.fee = fee;
        mAmountView.setText(Rx.formatPrice(amount));
        mFeeView.setText(Rx.formatPrice(fee));
    }

    @Override
    public TradeParams getTradeParams() {
        return mParams;
    }

    @Override
    public ProductInfo getProductInfo() {
        return mProductInfo;
    }

    @Override
    public void onTradeFailed(String msg) {
        mEnSureView.setEnabled(true);
        AppUI.dismiss();
        AppUI.failed(getContext(), mTitleView.getText() + "订货失败，" + msg);
        dismiss();
    }

    @Override
    public void onTradeSuccess(String msg) {
        //回调上层
        if (mOnListener != null) {
            mOnListener.onTradeSuccess();
        }
        mEnSureView.setEnabled(true);
        AppUI.dismiss();
        AppUI.success(getContext(), msg);
        dismiss();
    }

    @Override
    public void onTradeTimeout() {
        AppUI.dismiss();
        new DialogBuilder(getContext())
                .setMessage(mTitleView.getText() + "超时，请勿重复下单，是否现在前往订单中心？")
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .negativeButtonText("暂不")
                .positiveButtonText("立即前往")
                .negativeButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        dismiss();
                    }
                })
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        AppRouter.routeToOrderCenter(getActivity());
                        getActivity().finish();
                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onTradeExist() {
        AppUI.dismiss();
        new DialogBuilder(getContext())
                .setMessage("需先退订该品种后，才能再次预定")
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .negativeButtonHidden()
                .positiveButtonText("我知道了")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        mContext = context;
    }


    @Override
    public void onNotMoney() {
        dismiss();
        AppUI.dismiss();
        mEnSureView.setEnabled(true);
        new DialogBuilder(getContext())
                .setMessage("账户可用余额不足，前往充值？")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        RechargeHelper.toRecharge((Activity) mContext, (UserStatus) mContext);
//                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onLoadPercentSuccess(PercentInfo percentInfo) {
        Log.e(TAG, "onLoadPercentSuccess: "+percentInfo );
        switch (mProductInfo.getArea()){
            case "LMCADS03":
                tvBuyPercent.setText(percentInfo.getTXJ()+"%");
                tvSellPercent.setText(percentInfo.getTJSJ()+"%");
                break;
            case "XAG" :
                tvBuyPercent.setText(percentInfo.getBYXJ()+"%");
                tvSellPercent.setText(percentInfo.getBYJSJ()+"%");
                break;
            case "XAU" :
                tvBuyPercent.setText(percentInfo.getHJXJ()+"%");
                tvSellPercent.setText(percentInfo.getHJJSJ()+"%");
                break;
        }
    }

    public void notifychange(List<ProductInfo> mDataList) {
        if (mlist == null) return;
        if (mDataList == null) return;
        mlist = (ArrayList<ProductInfo>) mDataList;
        for (ProductInfo info : mlist) {
            for (ProductInfo info2 : mDataList) {
                if (info.getProductId().equals(info2.getProductId())) {
                    info.setLastPrice(info2.getLastPrice());
                }
            }
        }
        toTradeGoodsAdapter.notifyDataSetChanged();
    }

    @Subscribe
    @Override
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        lastPrices = new ArrayList<>();
        for (int i = 0; i < mlist.size(); i++) {
            QuotationInfo quotationInfo = quotations.get(Rx.parseInt(mlist.get(i).getProductId()));
            lastPrices.add(quotationInfo.getLast());
        }
        if (toTradeGoodsAdapter == null) return;
        toTradeGoodsAdapter.setLastPrices(lastPrices);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mCustomerQuantityText.removeTextChangedListener(mTextWatcher);
        unbinder.unbind();
    }


    /**
     * call back
     */
    public interface OnTradeSuccessListener {

        /**
         * 交易成功
         */
        void onTradeSuccess();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnTradeSuccessListener) {
            mOnListener = (OnTradeSuccessListener) context;
        }
    }

}
